"""
Case Type   : 事务控制
Case Name   : 多事务并发加锁，查询主备数据一致性
Create At   : 2024-07-12
Owner       : songjing20
Description :
    1.主机执行建表
    2.打开控制并发执行开关，且最大并发数为2，并发执行事务，关闭并发执行
    3.备机查询
    4.清理环境
Expect      :
    1.执行成功
    2.执行成功
    3.两次查询结果一致
    4.成功
History     :
"""
import os
import unittest

from yat.test import Node
from yat.test import macro
from testcase.utils.Logger import Logger
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant

Primary_SH = CommonSH('PrimaryDbUser')


@unittest.skipIf(2 > Primary_SH.get_node_num(), '单机环境不执行')
class Transaction(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.std1_sh = CommonSH('Standby1DbUser')
        self.node_pri = Node('PrimaryDbUser')
        self.constant = Constant()
        self.tb_name = 't_transaction_0117'
        self.file_abspath = os.path.join(
            macro.DB_BACKUP_PATH, f"{self.tb_name}.sql")

    def test_transaction_(self):
        text = '-----step1:主机执行建表;expect:成功-----'
        self.log.info(text)
        sql = f'''drop table if exists {self.tb_name} cascade;
        create table {self.tb_name}(a int primary key, b int);
        insert into {self.tb_name} values(1, 1);'''
        sql_res = self.pri_sh.execut_db_sql(sql)
        self.log.info(sql_res)
        self.assertIn(self.constant.CREATE_TABLE_SUCCESS, sql_res,
                      f'执行失败:{text}')
        self.assertIn(self.constant.INSERT_SUCCESS_MSG, sql_res,
                      f'执行失败:{text}')

        text = '-----step2:打开控制并发执行开关，且最大并发数为2，并发执行事务，关闭并发执行件;expect:成功-----'
        self.log.info(text)
        self.log.info('----- 创建sql文件 -----')
        content = f'''\parallel on 2
        begin
        update {self.tb_name} set b = b + 1 where a = 1;
        perform pg_sleep(2);
        end;
        /
        begin
        perform pg_sleep(1);
        perform * from {self.tb_name} where a = 1 for key share;
        perform pg_sleep(3);
        end;
        /
        \parallel off'''
        cmd = f'echo "{content}" > {self.file_abspath};cat {self.file_abspath};'
        self.log.info(cmd)
        cmd_res = self.node_pri.sh(cmd).result()
        self.log.info(cmd_res)
        self.log.info('----- gsql -f 执行sql文件-----')
        sql_cmd = f"source {macro.DB_ENV_PATH};" \
                  f"gsql -d {self.node_pri.db_name} " \
                  f"-p {self.node_pri.db_port} -f {self.file_abspath}"
        self.log.info(sql_cmd)
        sql_res = self.node_pri.sh(sql_cmd).result()
        self.log.info(sql_res)
        self.assertIn('Parallel is on with scale 2.\nParallel is off.', sql_res,
                      f'执行失败:{text}')
        self.assertEqual(
            sql_res.count(self.constant.CREATE_ANONYMOUS_BLOCK_SUCCESS_MSG),
            2, f'执行失败:{text}')

        text = '-----step3:备机查询;expect:两次查询结果一致-----'
        self.log.info(text)
        res = self.std1_sh.execut_db_sql(
            f'''explain select * from {self.tb_name};
            select * from {self.tb_name};
            explain select * from {self.tb_name} where a = 1;
            select * from {self.tb_name} where a = 1;''')
        self.log.info(res)
        self.assertEqual(res.count(' 1 | 2\n(1 row)'), 2, f'执行失败:{text}')
        self.assertTrue('Seq Scan' in res and 'Index Scan' in res,
                        f'执行失败:{text}')

    def tearDown(self):
        text = '-----step4:清理环境;expect:成功-----'
        self.log.info(text)
        drop_res = self.pri_sh.execut_db_sql(
            f"drop table if exists {self.tb_name} cascade;")
        self.log.info(drop_res)
        cmd = f'rm -f {self.file_abspath};echo $?;'
        self.log.info(cmd)
        cmd_res = self.node_pri.sh(cmd).result()
        self.log.info(cmd_res)
        self.assertIn(self.constant.TABLE_DROP_SUCCESS, drop_res,
                      f'删表失败:{text}')
        self.assertEqual('0', cmd_res, f'执行失败:{text}')
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
